package com.pz.gulimall.ware.service.impl;

import com.pz.gulimall.common.constant.WareConstant;
import com.pz.gulimall.ware.entity.PurchaseDetailEntity;
import com.pz.gulimall.ware.service.PurchaseDetailService;
import com.pz.gulimall.ware.service.WareSkuService;
import com.pz.gulimall.ware.vo.req.MergeReqVo;
import com.pz.gulimall.ware.vo.req.PurchaseDoneItem;
import com.pz.gulimall.ware.vo.req.PurchaseDoneReqVo;
import org.springframework.stereotype.Service;

import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.gulimall.common.utils.PageUtils;
import com.pz.gulimall.common.utils.Query;

import com.pz.gulimall.ware.dao.PurchaseDao;
import com.pz.gulimall.ware.entity.PurchaseEntity;
import com.pz.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Resource
    private PurchaseDetailService purchaseDetailService;
    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0").or().eq("status", "1");

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并，purchase_detail做修改操作
     * @param vo
     * /**
     *      * {
     *      *   purchaseId: 1, //整单id，可为空
     *      *   items:[1,2,3,4] //合并项 商品id集合
     *      * }
     *      */
    @Transactional
    @Override
    public void Merge(MergeReqVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if(purchaseId == null){
            //新建采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter( filter -> {
            //状态为 非采购
            return filter.getStatus() != WareConstant.PurchaseDetailStatusEnum.BUYING.getCode();
        }).collect(Collectors.toList());
        if(list.size() > 0){
            //设置更新时间
            purchaseDetailService.updateBatchById(list);
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(finalPurchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }

    }

    @Transactional
    @Override
    public void received(List<Long> purchaseIds) {
        if(purchaseIds != null && purchaseIds.size() > 0){
            List<PurchaseEntity> purchaseEntities = purchaseIds.stream().map(id -> {
                PurchaseEntity purchase = this.getById(id);
                return purchase;
            }).filter(item -> {
                //将状态是 新建 或 已分配 的过滤出来
                return item.getStatus()==WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                        item.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
            }).map(newItem -> {
                //设置新状态：已领取; 设置更新时间
                newItem.setUpdateTime(new Date());
                newItem.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                return newItem;
            }).collect(Collectors.toList());
            this.updateBatchById(purchaseEntities);

            //改变采购项 状态为正在采购
            purchaseEntities.forEach( item -> {
                List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByPurchaseId(item.getId());
                List<PurchaseDetailEntity> newDetail = purchaseDetailEntities.stream().map(detail -> {
                    detail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                    return detail;
                }).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(newDetail);
            });
        }
    }

    @Transactional
    @Override
    public void donePurchase(PurchaseDoneReqVo vo) {
        //改变 采购单状态
        PurchaseEntity purchase = getById(vo.getId());
        List<PurchaseDoneItem> items = vo.getItems();
        boolean success = true;

        List<PurchaseDetailEntity> updateDetails = new ArrayList<>();
        for (PurchaseDoneItem item : items){
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setId(item.getItemId());
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAIL.getCode()){
                success = false;
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.FAIL.getCode());
            }else {
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将采购成功的 purchaseDetail 入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity);
            }
            updateDetails.add(detail);
        }

        // 更新 采购项
        if(updateDetails.size()>0){
            purchaseDetailService.updateBatchById(updateDetails);
        }

        if(success){
            purchase.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else {
            purchase.setStatus(WareConstant.PurchaseStatusEnum.ERROR.getCode());
        }
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }

}